package com.baitai.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baitai.common.core.domain.entity.UpdateUsersRequest;
import com.baitai.common.utils.LogUtils;
import com.baitai.system.domain.SysUseConsigneeInfo;
import com.baitai.system.domain.vo.SysUserVo;
import com.baitai.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.baitai.common.annotation.Log;
import com.baitai.common.core.controller.BaseController;
import com.baitai.common.core.domain.AjaxResult;
import com.baitai.common.core.domain.entity.SysDept;
import com.baitai.common.core.domain.entity.SysRole;
import com.baitai.common.core.domain.entity.SysUser;
import com.baitai.common.core.page.TableDataInfo;
import com.baitai.common.enums.BusinessType;
import com.baitai.common.utils.SecurityUtils;
import com.baitai.common.utils.StringUtils;
import com.baitai.common.utils.poi.ExcelUtil;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;


    @Autowired
    private ISysUseConsigneeInfoService consigneeInfoService;


    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }


    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
//        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    /**
     * 根据用户手机号获取详细信息
     */
    @PostMapping(value = {"/phone"})
    public AjaxResult phone(@Validated @RequestBody SysUser user) {
        userService.checkPhoneUnique(user);
        if (StringUtils.isNotNull(user.getPhonenumber())) {
            SysUser sysUser = userService.selectUserByPhonenumber(user.getPhonenumber());
            if (sysUser != null) {
                return AjaxResult.success(sysUser);
            } else {
                return AjaxResult.success("未查询到用户");
            }
        } else {
            return AjaxResult.error("请输入手机号");
        }
    }


    /**
     * 新增用户
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
//        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUserPoints("0");
        user.setTotalPoints("0");
        user.setParentId(SecurityUtils.getUserId() + "");
        SysUser parent = userService.selectUserById(SecurityUtils.getUserId());
        if (StringUtils.isNotEmpty(parent.getAncestor())) {
            user.setAncestor(parent.getAncestor() + "," + parent.getUserId());
        } else {
            user.setAncestor(parent.getUserId() + "");
        }

        user.setAvatar("/profile/avatar/logo.png");
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
//        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 状态修改
     */
    @Log(title = "用户注销", businessType = BusinessType.UPDATE)
    @PostMapping("/unsubscribe")
    public AjaxResult unsubscribe(@RequestBody SysUser user) {
        user.setUserId(SecurityUtils.getUserId());
        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
//        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/getRoles")
    public AjaxResult getRoles() {
        return success(roleService.selectRoleAll());
    }


    @GetMapping("/consigneeInfoList")
    public AjaxResult consigneeInfoList() {
        startPage();
        SysUseConsigneeInfo sysUseConsigneeInfo = new SysUseConsigneeInfo();
        sysUseConsigneeInfo.setUserId(SecurityUtils.getUserId());
        List<SysUseConsigneeInfo> list = consigneeInfoService.selectSysUseConsigneeInfoList(sysUseConsigneeInfo);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 新增收货人信息
     */
    @Log(title = "收货人信息", businessType = BusinessType.INSERT)
    @PostMapping("/addConsigneeInfo")
    public AjaxResult addConsigneeInfo(@RequestBody SysUseConsigneeInfo sysUseConsigneeInfo) {
        sysUseConsigneeInfo.setUserId(SecurityUtils.getUserId());
        return toAjax(consigneeInfoService.insertSysUseConsigneeInfo(sysUseConsigneeInfo));
    }

    /**
     * 修改收货人信息
     */
    @Log(title = "收货人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateConsigneeInfo")
    public AjaxResult updateConsigneeInfo(@RequestBody SysUseConsigneeInfo sysUseConsigneeInfo) {
        return toAjax(consigneeInfoService.updateSysUseConsigneeInfo(sysUseConsigneeInfo));
    }

    /**
     * 获取收货人信息详细信息
     */
    @GetMapping(value = "consigneeInfo/{id}")
    public AjaxResult getConsigneeInfo(@PathVariable("id") Long id) {
        return success(consigneeInfoService.selectSysUseConsigneeInfoById(id));
    }

    /**
     * 删除收货人信息
     */
    @Log(title = "收货人信息", businessType = BusinessType.DELETE)
    @PostMapping("deleteConsigneeInfo/{ids}")
    public AjaxResult deleteConsigneeInfo(@PathVariable Long[] ids) {
        return toAjax(consigneeInfoService.deleteSysUseConsigneeInfoByIds(ids));
    }

    /**
     * 积分排行榜
     */
    @GetMapping(value = "/rankingList")
    public AjaxResult rankingList() {
//        startPage();
//        List<SysUser> list = userService.selectRankingList();
        List<SysUser> list = new ArrayList<>();
        return AjaxResult.success(getDataTable(list));
    }


    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/updateUser")
    public AjaxResult updateUser(@Validated @RequestBody SysUser user) {
        user.setUserId(SecurityUtils.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.appUpdateUser(user));
    }

        /**
         * 批量修改用户
         */
        @PostMapping("/updateUserList")
        public AjaxResult updateUserList(@RequestBody UpdateUsersRequest updateUsersRequest) {
            String parentId = updateUsersRequest.getParentId();
            String ancestor = updateUsersRequest.getAncestor();
            Long []idList = updateUsersRequest.getIdList().toArray(new Long[updateUsersRequest.getIdList().size()]);
            if (parentId == null || StringUtils.isEmpty(ancestor)) {
                return error("请填写父级 ID 和上下级关系");
            }
            try {
                // 调用服务层方法进行批量更新
                int rows = userService.updateUserList(Long.parseLong(parentId), ancestor, idList);
                return toAjax(rows);
            } catch (Exception e) {
                // 记录异常日志
                // 这里可以使用日志框架，如 SLF4J 记录异常信息
                System.out.println(e.getMessage());
                return error("批量更新用户信息时出现异常，请稍后重试");
            }
        }

    /**
     * 修改用户
     */
    @PostMapping("/myTeam")
    public AjaxResult myTeam() {
        return AjaxResult.success(userService.myTeam(SecurityUtils.getUserId()));
    }


    /**
     * 修改用户
     */
    @PostMapping("/getUserInfo")
    public AjaxResult getUserInfo() {
        return AjaxResult.success(userService.getUserInfo(SecurityUtils.getUserId()));
    }

    /**
     * 修改用户
     */
    @PostMapping("/setAncestor")
    public AjaxResult setAncestor() {
        return AjaxResult.success(userService.setAncestor());
    }

    /**
     * 上下级列表
     */
    @GetMapping("/superiorAndSubordinateList")
    public TableDataInfo superiorAndSubordinateList(SysUser user) {
        startPage();
        List<SysUserVo> list = userService.selectUserVoList(user);
        return getDataTable(list);
    }

    /**
     * 上下级列表
     */
    @GetMapping("/initPrizeCount")
    public AjaxResult initPrizeCount(Long start, Long stop) {
        return AjaxResult.success(userService.initPrizeCount(start, stop));
    }


    /**
     * 上下级列表
     */
    @GetMapping("/getPrizeCount")
    public AjaxResult getPrizeCount() {
        return AjaxResult.success(userService.getPrizeCount(SecurityUtils.getUserId()));
    }
}
